package com.dalianpai.gulimall.cart.service.impl;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.TypeReference;
import com.dalianpai.common.utils.R;
import com.dalianpai.gulimall.cart.feign.ProductFeignService;
import com.dalianpai.gulimall.cart.interceptor.CartInterceptor;
import com.dalianpai.gulimall.cart.service.CartService;
import com.dalianpai.gulimall.cart.vo.Cart;
import com.dalianpai.gulimall.cart.vo.CartItem;
import com.dalianpai.gulimall.cart.vo.SkuInfoVo;
import com.dalianpai.gulimall.cart.vo.UserInfoVo;
import org.apache.commons.lang.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.BoundHashOperations;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.stereotype.Service;

import java.math.BigDecimal;
import java.util.List;
import java.util.concurrent.CompletableFuture;
import java.util.concurrent.ExecutionException;
import java.util.concurrent.ThreadPoolExecutor;
import java.util.stream.Collectors;

/**
 * @author WGR
 * @create 2020/7/22 -- 20:50
 */
@Service
public class CartServiceImpl implements CartService {

    @Autowired
    StringRedisTemplate redisTemplate;

    @Autowired
    ProductFeignService productFeignService;

    @Autowired
    ThreadPoolExecutor poolExecutor;


    private final String CART_PREFIX ="gulimall:cart:";

    @Override
    public CartItem addToCart(Long skuId, Integer num) throws ExecutionException, InterruptedException {
        BoundHashOperations<String, Object, Object> cartOps = getCartOps();
        //2。商品添加到购物车


        String  res = (String) cartOps.get(skuId.toString());
        if(StringUtils.isEmpty(res)){
            CartItem cartItem = new CartItem();
            CompletableFuture<Void> set1 = CompletableFuture.runAsync(() -> {
                R r = productFeignService.info(skuId);
                SkuInfoVo data = r.getData("skuInfo", new TypeReference<SkuInfoVo>() {
                });
                cartItem.setCheck(true);
                cartItem.setCount(num);
                cartItem.setImages(data.getSkuDefaultImg());
                cartItem.setTitle(data.getSkuTitle());
                cartItem.setSkuId(skuId);
                cartItem.setPrice(data.getPrice());
            }, poolExecutor);

            CompletableFuture<Void> set2 = CompletableFuture.runAsync(() -> {
                List<String> skuSaleAttrValues = productFeignService.getSkuSaleAttrValues(skuId);
                cartItem.setSkuAttr(skuSaleAttrValues);
            }, poolExecutor);

            CompletableFuture.allOf(set1,set2).get();

            String s = JSON.toJSONString(cartItem);
            cartOps.put(skuId.toString(),s);
            return cartItem;
        }else{
            CartItem cartItem = JSON.parseObject(res,CartItem.class);
            cartItem.setCount(cartItem.getCount()+num);
            cartOps.put(skuId.toString(),JSON.toJSONString(cartItem));
            return cartItem;
        }


    }

    @Override
    public CartItem getCartItem(Long skuId) {
        BoundHashOperations<String, Object, Object> cartOps = getCartOps();
        String s = (String) cartOps.get(skuId.toString());
        return JSON.parseObject(s,CartItem.class);
    }

    @Override
    public Cart getCart() throws ExecutionException, InterruptedException {
        Cart cart = new Cart();
        UserInfoVo userInfoVo = CartInterceptor.threadLocal.get();
        System.out.println(userInfoVo);
        if(userInfoVo.getUserId()!=null){
            String cartKey = CART_PREFIX+ userInfoVo.getUserId();
            //2.先去拿到临时购物车里面的数据
            String tempCartKey = CART_PREFIX+ userInfoVo.getUserKey();
            List<CartItem> tempcartItems = getCartItems(tempCartKey);
            if(tempcartItems !=null){
                for(CartItem item:tempcartItems){
                    addToCart(item.getSkuId(),item.getCount());
                }
                clearKey(tempCartKey);
            }

            //3.获取登录后的购物车的数据【包含合并过来的临时购物车数据和登录后的购物车数据】
            List<CartItem> cartItems = getCartItems(cartKey);
            cart.setItem(cartItems);
        }else{
          String userKey =   CART_PREFIX + userInfoVo.getUserKey();
            List<CartItem> cartItems = getCartItems(userKey);
            cart.setItem(cartItems);
        }

        return cart;
    }

    @Override
    public void clearKey(String cartKey) {
       redisTemplate.delete(cartKey);
    }

    @Override
    public void checkItem(Long skuId, Integer check) {
        BoundHashOperations<String, Object, Object> cartOps = getCartOps();
        CartItem cartItem = getCartItem(skuId);
        cartItem.setCheck(check==1?true:false);
        String s = JSON.toJSONString(cartItem);
        cartOps.put(skuId.toString(),s);
        System.out.println("1234");
    }

    @Override
    public void checkCount(Long skuId, Integer num) {
        CartItem cartItem = getCartItem(skuId);
        cartItem.setCount(num);
        BoundHashOperations<String, Object, Object> cartOps = getCartOps();
        cartOps.put(skuId.toString(),JSON.toJSONString(cartItem));
    }

    @Override
    public void deleteItem(Long skuId) {
        BoundHashOperations<String, Object, Object> cartOps = getCartOps();
        cartOps.delete(skuId.toString());
    }

    @Override
    public List<CartItem> getUserCartItems() {
        UserInfoVo userInfoVo = CartInterceptor.threadLocal.get();
        System.out.println(userInfoVo);
        if(userInfoVo.getUserId() ==null){
            return null;
        }else{
            String cartKey = CART_PREFIX+userInfoVo.getUserId();
            List<CartItem> cartItems = getCartItems(cartKey);
            List<CartItem> collect = cartItems.stream().filter(item -> item.getCheck())
                    .map(item -> {
                        R price = productFeignService.getPrice(item.getSkuId());
                        item.setPrice(new BigDecimal ((String)price.get("data")));
                        return item;
                    }).collect(Collectors.toList());
            return collect;
        }

    }

    public BoundHashOperations<String, Object, Object> getCartOps() {
        UserInfoVo userInfoVo = CartInterceptor.threadLocal.get();
        String cartKey ="";
        if(userInfoVo.getUserId() !=null){
            cartKey = CART_PREFIX + userInfoVo.getUserId();
        }else{
            cartKey = CART_PREFIX + userInfoVo.getUserKey();
        }

        BoundHashOperations<String, Object, Object> operations = redisTemplate.boundHashOps(cartKey);
        
        return operations;
    }

    private List<CartItem> getCartItems(String cartKey){
        BoundHashOperations<String, Object, Object> hashOps = redisTemplate.boundHashOps(cartKey);
        List<Object> values = hashOps.values();
        if(values !=null && values.size()>0){
            List<CartItem> cartItems = values.stream().map((obj) -> {
                String str = (String) obj;
                CartItem cartItem = JSON.parseObject(str, CartItem.class);
                return cartItem;
            }).collect(Collectors.toList());
            return cartItems;
        }
        return null;
    }


}
